import 'dart:async';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:shopping_group/event/event.dart';

import 'package:shopping_group/main/lz_mall/model/lz_mall_category_model.dart';
import 'package:shopping_group/main/lz_mall/model/lz_mall_category_prduct_model.dart';
import 'package:shopping_group/main/lz_mall/provider/lz_mall_home_provider.dart';
import 'package:shopping_group/main/lz_mall/view_model/lz_mall_home_view_model.dart';
import 'package:shopping_group/main/lz_mall/widgets/lz_mall_home_category_item_widget.dart';
import 'package:shopping_group/modle/main/bloc/main_data_bloc.dart';
import 'package:shopping_group/modle/main/entity/commo_spec4app_record_entity.dart';
import 'package:shopping_group/modle/main/entity/id_name_entity.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:provider/provider.dart';

import '../../../modle/main/ui/details_page.dart';

class LzMallHomePage extends StatefulWidget {
  @override
  _LzMallHomePageState createState() => _LzMallHomePageState();
}

class _LzMallHomePageState extends State<LzMallHomePage> with TickerProviderStateMixin {
  GZXDropdownMenuController _dropdownMenuController = GZXDropdownMenuController();

  GlobalKey _stackKey = GlobalKey();
  String _typeId = 'TYPE';
  List<CommoSpec4AppRecordEntity> _list = [];
  Map<String, List<CommoSpec4AppRecordEntity>> _maplist = {};
  MainDataBloc _bloc;

  List<IdNameEntity> _listType = [];

  IdNameEntity _selectIdNameEntity;
  StreamSubscription _loginSubscription;

  TabController _tabController;
  TabController _subTabController;

  bool _isSubCatogery = false;

  @override
  void initState() {
    super.initState();
    _loginSubscription = eventBus.on<BlackForumEvent>().listen((event) {
      if (!mounted) {
        return;
      }
      LzMallHomeViewModel().getCatogery(context, (value) {
        _tabController = TabController(length: value.length, vsync: this);
        _subTabController = TabController(length: value.length, vsync: this);
        Provider.of<LzMallHomeProvider>(context, listen: false).setCategoryModels(value);
      });
    });
  }

  @override
  void dispose() {
    _loginSubscription?.cancel();
    super.dispose();
  }

  ///头图
  Widget _buildSwiperView() {
    return AspectRatio(
      aspectRatio: 375 / 100,
      child: Image.asset(
        'images/icon_shop_mian.png',
        fit: BoxFit.fitWidth,
      ),
    );
  }

  Widget _buildTabbarWidget(LzMallHomeProvider value) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 10),
      color: Colors.white,
      child: TabBar(
          tabs: value.categoryModels.map((LzMallCategoryModel categoryModel) {
            return Text(categoryModel.name);
          }).toList(),
          indicatorColor: Theme.of(context).primaryColor,
          labelColor: Theme.of(context).primaryColor,
          unselectedLabelColor: Color(0xFF666666),
          indicatorSize: TabBarIndicatorSize.label,
          onTap: (index) {
            LzMallCategoryModel productModel = value.categoryModels[index];
            String code = productModel.id;
            _isSubCatogery = false;
            List<LzCategoryProductModel> productModels = value.dataMap[code];
            if (productModels != null && productModels.length > 0) {
            } else {
              LzMallHomeViewModel().getCategoryProduct(context, code);
            }
            value.setCurrentCategoryModels(productModel);
            if (productModel.children.length == 0) {
              return;
            }
            _subTabController = TabController(length: productModel.children.length, vsync: this);
          },
          controller: _tabController),
    );
  }

  Widget _buildSubTabbarWidget(LzMallHomeProvider value) {
    if (value.currentCategoryModels == null) return Container();
    if (value.currentCategoryModels.children.isEmpty) return Container();

    LzMallCategoryModel currentSubCategoryModels = value.currentSubCategoryModels;

    return Container(
      padding: EdgeInsets.symmetric(vertical: 10),
      color: Colors.white,
      child: TabBar(
          tabs: value.currentCategoryModels.children.map((LzMallCategoryModel subCategoryModel) {
            return Text(subCategoryModel.name,
                style: TextStyle(
                  color: (currentSubCategoryModels.id == subCategoryModel.id && _isSubCatogery)
                      ? Theme.of(context).primaryColor
                      : Color(0xFF666666),
                  fontSize: 12,
                ));
          }).toList(),
          indicator: const BoxDecoration(),
          // indicatorPadding: EdgeInsets.symmetric(horizontal: 5),
          labelPadding: EdgeInsets.symmetric(horizontal: 5),
          // isScrollable: true,
          onTap: (index) {
            LzMallCategoryModel subCategoryModel = value.currentCategoryModels.children[index];
            _isSubCatogery = true;
            String code = subCategoryModel.id;

            List<LzCategoryProductModel> productModels = value.dataMap[code];
            if (productModels != null && productModels.length > 0) {
              value.setCurrentSubCategoryModels(subCategoryModel);
            } else {
              value.setCurrentSubCategoryModels(subCategoryModel);

              LzMallHomeViewModel().getSubCategoryProduct(context, code);
            }
          },
          controller: _subTabController),
    );
  }

  ///展示商品列表
  _buildMallProductWidget(LzMallHomeProvider value) {
    //获取当前数据
    List<LzCategoryProductModel> productModels = value.productModel ?? [];

    return Expanded(
        child: Container(
      child: ListView.builder(
        itemBuilder: (BuildContext context, int index) {
          return LzMallHomeCategoryItemWidget(productModels[index]);
        },
        itemCount: productModels.length,
      ),

      //  GridView.builder(
      //   padding: EdgeInsets.zero,
      //   controller: ScrollController(keepScrollOffset: false), //靜止滾動事件
      //   gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
      //       crossAxisCount: 2, crossAxisSpacing: 1, mainAxisSpacing: 1, childAspectRatio: 12 / 16), //子纵比例
      //   shrinkWrap: true, //收缩包装
      //   itemBuilder: (context, index) {
      //     return GestureDetector(
      //       onTap: () {},
      //       child: Container(
      //         decoration: BoxDecoration(
      //           color: Colors.white,
      //           //设置四周圆角 角度
      //           borderRadius: BorderRadius.circular(12),
      //         ),
      //         child: Text("data"),
      //       ),
      //     );
      //   },
      //   itemCount: productModels.length,
      // ),
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Color(0xFFF4F4F4),
        appBar: AppBar(
            elevation: 0.0,
            backgroundColor: Theme.of(context).primaryColor,
            title: WidgetUtils.getTextColorView("利正生活商城", Colors.white, Dimens.FONT_SIZE_20),
            centerTitle: true),
        body: Consumer<LzMallHomeProvider>(builder: (context, value, child) {
          List<LzMallCategoryModel> categoryModels = value.categoryModels ?? [];
          if (categoryModels.length == 0) return _buildSwiperView();
          return Container(
            child: Column(
              children: [
                _buildSwiperView(),
                _buildTabbarWidget(value),
                _buildSubTabbarWidget(value),
                _buildMallProductWidget(value),
              ],
            ),
          );
        }));

    Scaffold(
        appBar: WidgetUtils.showApparNotLeading(context, '利正生活商城',
            isCenterTitle: true, textColor: Colors.white, onTapCall: (e) {}),
        backgroundColor: Colors.white,
        body: StreamBuilder(
            stream: _bloc.sendTypeData,
            initialData: _listType,
            builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
              Object object = snapshot.data;
              List<GZXDropDownHeaderItem> headerItems = [];
              List<GZXDropdownMenuBuilder> menuBuilder = [];

              if (object is List) {
                _listType = object;
                _listType.forEach((element) {
                  bool isSelect = false;
                  if (element.children.length == 0) {
                    //无子分类
                    isSelect = element.isSelect;
                    if (isSelect) {
                      _selectIdNameEntity = element;
                    }
                  } else {
                    //有子分类
                    element.children.forEach((IdNameEntity elementChildren) {
                      if (elementChildren.isSelect) {
                        isSelect = true;
                      }
                    });
                  }

                  Color textColor = Color(0xFF666666);
                  if (isSelect) {
                    textColor = Theme.of(context).primaryColor;
                  }

                  if (_selectIdNameEntity != null) {
                    if (element.children.length == 0 && element.isSelect) {
                      textColor = Theme.of(context).primaryColor;
                    } else {
                      textColor = Color(0xFF666666);
                    }
                  }

                  headerItems.add(GZXDropDownHeaderItem(element.name,
                      style: TextStyle(color: textColor), iconSize: element.children.length == 0 ? 0 : 20));

                  menuBuilder.add(GZXDropdownMenuBuilder(
                      dropDownHeight: 40.0 * element.children.length,
                      dropDownWidget: _buildConditionListWidget(element.children, (IdNameEntity value) {
                        // _dropDownHeaderItemStrings[2] = _selectNameEntity.name;
                        _dropdownMenuController.hide();
                        _selectIdNameEntity?.isSelect = false;
                        _selectIdNameEntity = null;

                        _bloc.initMainData.add(_listType);

                        _typeId = value.id;
                        if (ObjectUtil.isEmptyList(_maplist[_typeId])) {
                          _bloc.initCommSpecData.add(_typeId);
                        } else {
                          _bloc.initCommSpecData.add(_maplist[_typeId]);
                        }
                      })));
                });
              }
              return Stack(
                key: _stackKey,
                children: <Widget>[
                  Column(
                    children: <Widget>[
                      _buildSwiperView(),
                      // 下拉菜单头部
                      GZXDropDownHeader(
                        // 下拉的头部项，目前每一项，只能自定义显示的文字、图标、图标大小修改
                        items: headerItems,
                        // GZXDropDownHeader对应第一父级Stack的key
                        stackKey: _stackKey,
                        // controller用于控制menu的显示或隐藏
                        controller: _dropdownMenuController,
                        // 当点击头部项的事件，在这里可以进行页面跳转或openEndDrawer
                        onItemTap: (index) {
                          IdNameEntity nameEntity = _listType[index];
                          if (nameEntity.children.length == 0) {
                            if (_selectIdNameEntity != null) {
                              _selectIdNameEntity.isSelect = false;
                            }
                            _selectIdNameEntity = nameEntity;
                            _selectIdNameEntity.isSelect = true;
                            _listType.forEach((IdNameEntity titleModel) {
                              titleModel.children.forEach((subElement) {
                                subElement.isSelect = false;
                              });
                            });
                            _dropdownMenuController.hide();

                            _bloc.initMainData.add(_listType);

                            _typeId = nameEntity.id;
                            if (ObjectUtil.isEmptyList(_maplist[_typeId])) {
                              _bloc.initCommSpecData.add(_typeId);
                            } else {
                              _bloc.initCommSpecData.add(_maplist[_typeId]);
                            }
                          }
                        },
                        style: TextStyle(color: Color(0xFF666666), fontSize: 14),
                        // 下拉时文字样式
                        dropDownStyle: TextStyle(fontSize: 14, color: Theme.of(context).primaryColor),
                        iconDropDownColor: Theme.of(context).primaryColor,
                      ),
                      Expanded(child: _showlistView()),
                    ],
                  ),
                  // 下拉菜单
                  GZXDropDownMenu(
                    // controller用于控制menu的显示或隐藏
                    controller: _dropdownMenuController,
                    // 下拉菜单显示或隐藏动画时长
                    animationMilliseconds: 300,
                    // 下拉后遮罩颜色
                    dropdownMenuChanging: (isShow, index) {},
                    dropdownMenuChanged: (isShow, index) {},
                    // 下拉菜单，高度自定义，你想显示什么就显示什么，完全由你决定，你只需要在选择后调用_dropdownMenuController.hide();即可
                    menus: menuBuilder,
                  ),
                ],
              );
            }));
  }

  Widget _showlistView() {
    return StreamBuilder(
      stream: _bloc.sendCommSpecData,
      initialData: null == _maplist[_typeId] ? _list : _maplist[_typeId],
      builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
        Object object = snapshot.data;
        if (object is List) {
          _maplist[_typeId] = [];

          if (ObjectUtil.isEmptyList(object)) {
            _maplist[_typeId] = [];
          } else {
            for (var item in object) {
              _maplist[_typeId].add(item);
            }
          }
        }
        int count = null == _maplist[_typeId] ? 0 : _maplist[_typeId].length;
        if (0 != count) {
          return Container(
            decoration: new BoxDecoration(
              color: Colors.white,
            ),
            child: RefreshIndicator(
              onRefresh: _pullToRefresh,
              child: GridView.builder(
                padding: EdgeInsets.zero,
                controller: ScrollController(keepScrollOffset: false), //靜止滾動事件
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2, crossAxisSpacing: 1, mainAxisSpacing: 1, childAspectRatio: 12 / 16), //子纵比例
                shrinkWrap: true, //收缩包装
                itemBuilder: buildItem,
                itemCount: _maplist[_typeId].length,
              ),
            ),
          );
        } else {
          return Container(
            alignment: Alignment.center,
            child: WidgetUtils.emptyView(
              contexts,
            ),
          );
        }
      },
    );
  }

  Future _pullToRefresh() async {
    _maplist[_typeId]?.clear();
    _bloc.refreshDate.add(_typeId);
    return null;
  }

  //ListView的Item
  Widget buildItem(BuildContext context, int index) {
    return Container(
      // margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: GestureDetector(
          onTap: () {
            // if (!BaseConstant.isLogin) {
            //   RouteUtil.goView(PageConstance.LOGIN_PAGE);
            //   return;
            // }
            // BaseConstant.openShopId = _maplist[_typeId][index].id;
            // RouteUtil.goView(PageConstance.DETAILS_PAGE);
            RouteUtil.goParameter(DetailsPage(id: _maplist[_typeId][index].id));
          },
          child: _xunchaItem(_maplist[_typeId][index])),
    );
  }

  Widget _xunchaItem(CommoSpec4AppRecordEntity entity) {
    return Container(
      padding: const EdgeInsets.all(8),
      child: Container(
        child: Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.fromLTRB(8, 8, 8, 0),
              child: AspectRatio(
                aspectRatio: 1,
                child: FadeInImage.assetNetwork(
                  image: entity.imgUrl,
                  placeholder: 'images/picture_loading.png',
                  fit: BoxFit.contain,
                ),
              ),
            ),
            Container(
                padding: EdgeInsets.only(top: 6),
                child:
                    WidgetUtils.getTextMaxLinesView(entity.name, Colours.text_2222, Dimens.FONT_SIZE_14, maxLines: 2)),
            Container(
              padding: const EdgeInsets.only(right: 8, top: 5),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Container(
                    child: Text(
                      "¥" + entity.outPrice,
                      style: TextStyle(
                        color: Color(0xFFF5544B),
                        fontSize: Dimens.FONT_SIZE_14,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Container(
                    alignment: Alignment.centerLeft,
                    child: WidgetUtils.getTextColorView(
                        '已售 ${entity.hadShopCt} 件', Colours.text_2222, Dimens.FONT_SIZE_12,
                        overflow: TextOverflow.clip),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  _buildConditionListWidget(List<IdNameEntity> items, void itemOnTap(IdNameEntity nameEntity)) {
    if (items.length == 0) return Container();
    return ListView.separated(
      shrinkWrap: true,
      scrollDirection: Axis.vertical,
      itemCount: items.length,
      // item 的个数
      separatorBuilder: (BuildContext context, int index) => Divider(height: 1.0),
      // 添加分割线
      itemBuilder: (BuildContext context, int index) {
        IdNameEntity nameEntity = items[index];
        return GestureDetector(
          onTap: () {
            _listType.forEach((IdNameEntity titleModel) {
              titleModel.children.forEach((subElement) {
                subElement.isSelect = false;
              });
            });

            nameEntity.isSelect = true;

            itemOnTap(nameEntity);
          },
          child: Container(
            //            color: Colors.blue,
            height: 40,
            child: Row(
              children: <Widget>[
                SizedBox(
                  width: 16,
                ),
                Expanded(
                  child: Text(
                    nameEntity.name,
                    style: TextStyle(
                      color: nameEntity.isSelect ? Theme.of(context).primaryColor : Colors.black,
                    ),
                  ),
                ),
                nameEntity.isSelect
                    ? Icon(
                        Icons.check,
                        color: Theme.of(context).primaryColor,
                        size: 16,
                      )
                    : SizedBox(),
                SizedBox(
                  width: 16,
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
